package utils

import (
	"errors"
	"fmt"
	"github.com/dop251/goja"
	"github.com/sirupsen/logrus"
	"go.k6.io/k6/js/compiler"
	"nextFlow/types"
)

var log = logrus.New()

func TransformES5(str string) string {
	c := compiler.New(log)
	src, _, _ := c.Transform(str, "main.js", nil)
	return src
}

func JsDo(config types.H) (out interface{}, err error) {

	jsPath := config.Get("src").String()
	funcName := config.Get("func").String()

	var params []goja.Value
	var initParams []goja.Value

	jsEngine := NewGojaJsEngine("", "", nil)
	entrypoint, e := jsEngine.Execute("require", jsPath)

	if e != nil {
		return nil, e
	}

	mainjs, ok := entrypoint.(*goja.Object)

	if !ok {
		return nil, errors.New("is not a function")
	}

	init, ok := goja.AssertFunction(mainjs.Get("init"))

	if !ok {
		return nil, errors.New("init is not a function")
	}

	for _, initParamsKey := range ParseJSFunctionParams(mainjs.Get("init").ToString().String()) {
		initParams = append(initParams, jsEngine.ToValue(config.Get(fmt.Sprintf("init.%s", initParamsKey)).Value()))
	}

	init(mainjs, initParams...)

	main, ok := goja.AssertFunction(mainjs.Get(funcName))

	if !ok {
		return nil, errors.New(funcName + " is not a function")
	}

	for _, mainParamsKey := range ParseJSFunctionParams(mainjs.Get(funcName).ToString().String()) {
		params = append(params, jsEngine.ToValue(config.Get(fmt.Sprintf("params.%s", mainParamsKey)).Value()))
	}

	res, err := main(mainjs, params...)

	if err == nil {

		out = res.Export()

		return out, err

	}

	return nil, err

}
